﻿using AutoMapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Zj.OpenAuth.Domain.Core;
using Zj.OpenAuth.Domain.Interface;
using Zj.OpenAuth.DTO.Common;

namespace Zj.OpenAuth.App.RoleApp
{
    /// <summary>
    /// role application service implement
    /// </summary>
    public class RoleAppService : IRoleAppService
    {
        public readonly IRoleRepository _repository;
        public RoleAppService(IRoleRepository repository)
        {
            this._repository = repository;
        }


        /// <summary>
        /// add or edit Role 
        /// </summary>
        /// <returns></returns>
        public bool AddOrEdit(RoleDTO dto)
        {
            Role role = Mapper.Map<RoleDTO, Role>(dto);
            if (dto.Id != 0 && Get(role.Id) != null)
            {
                role = _repository.Get(role.Id);
                role.Text = dto.Text;
                role.Code = dto.Code;
                role.Description = dto.Description;
                role.LastModifyTime = DateTime.Now;

                role = _repository.Update(role);
            }
            else
            {
                role = _repository.Insert(role);
            }
            return role == null ? false : true;
        }



        /// <summary>
        /// delete Role
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public void Delete(int id)
        {
            _repository.Delete(id);
        }


        public void DeleteMuti(List<int> ids)
        {
            ids.ForEach(id => _repository.Delete(id));
        }

        public RoleDTO Get(int id)
        {
            return Mapper.Map<Role, RoleDTO>(_repository.Get(id));
        }


        public List<RoleDTO> GetAllList()
        {
            return Mapper.Map<List<Role>, List<RoleDTO>>(_repository.Query(s => s.Status != StatusEnum.Deleted).ToList());
        }

        public List<RoleDTO> GetAllPageList(int pageIndex, out int rowCount, int pageSize = 10)
        {
            return Mapper.Map<List<Role>, List<RoleDTO>>(
                _repository.QueryPage(s => s.Status != StatusEnum.Deleted, pageSize, pageIndex, out rowCount, s => s.Id)
                .ToList());
        }

        public List<int> GetAllMenuListByRole(int value)
        {
            return _repository.GetAllMenuListByRole(value);
        }

        public List<int> GetAllRoleListByUser(int value)
        {
            return _repository.GetAllRoleListByUser(value);
        }

        public bool UpdateRoleMenu(int roleId, List<RoleMenuMappingDTO> roleMenus)
        {
            return _repository.UpdateRoleMenu(roleId, Mapper.Map<List<RoleMenuMappingDTO>, List<RoleMenuMapping>>(roleMenus));
        }
    }
}
